package in.muton.edushare.components.tasks.schedules.api;

import in.muton.edushare.wicket.models.CayenneList;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.wicket.model.IModel;

import com.edushare.common.vo.ScheduleNotifications;
import com.edushare.common.vo.Schedules;
import com.edushare.common.vo.Users;

public class ScheduleModel implements
		IModel<List<IModel<ScheduleNotifications>>> {

	public ScheduleModel(IModel<Users> userModel) {
		this.userModel = userModel;
	}

	private static final long serialVersionUID = 7524890594352863536L;

	public List<IModel<ScheduleNotifications>> getObject() {
		List<ScheduleNotifications> snList = userModel.getObject()
				.getSchedules();
		List<ScheduleNotifications> actual = new ArrayList<ScheduleNotifications>();

		for (ScheduleNotifications sn : snList) {
			if (sn.getActionStatus() == ScheduleNotifications.INVITED
					&& sn.getSchedule().getStatus() != Schedules.EVENT_STATUS_CANCELLED
					&& isEventInFuture(sn.getSchedule())) {
				actual.add(sn);
			}
		}
		return new CayenneList<ScheduleNotifications>(actual).getObject();
	}

	public void setObject(List<IModel<ScheduleNotifications>> arg0) {
	}

	public void detach() {
	}

	private IModel<Users> userModel;

	private static boolean isEventInFuture(Schedules sch) {
		if (sch.getFrequency() == Schedules.EVENT_ONCE_ONLY) {
			if (sch.getSchEnd().getTime() > new Date().getTime())
				return true;
		} else {
			if (sch.getRepetitionEnd().getTime() > new Date().getTime())
				return true;
		}
		return false;
	}
}
